﻿using MicroCloud.Dtos;
using System.Text;

namespace Vinno.Brand.Pack.Core.Events
{
    /// <summary>
    /// 反馈意见事件处理器
    /// </summary>
    public class SuggestEventHandler: EventHandlerBase<EntityEventData<Suggest>>
    {
        //字段
        private readonly IServiceProvider _provider;

        /// <summary>
        /// 初始化一个反馈意见事件处理器（<see cref="SuggestEventHandler"/>）的新实例
        /// </summary>
        /// <param name="provider">服务提供者</param>
        public SuggestEventHandler(IServiceProvider provider)
        {
            _provider = provider;
        }

        /// <summary>
        /// 获取 日志对象
        /// </summary>
        protected ILogger Logger => _provider.GetLogger(GetType());

        protected IEmailSender EmailSender => _provider.GetRequiredService<IEmailSender>();

        protected EmailOption Email => _provider.GetMicroCloudOptions().Email;

        protected IBrandService BrandService => _provider.GetService<IBrandService>();

        /// <summary>
        /// 事件处理
        /// </summary>
        /// <param name="eventData">事件源数据</param>
        public override void Handle(EntityEventData<Suggest> eventData, IServiceProvider provider)
        {
            if (!eventData.HasData() || eventData.OperateType != OperateType.Insert) return;

            EmailSenderOptions emailSender = Email?.Sender;
            Check.NotNull(emailSender, nameof(emailSender));

            var areaCodes = eventData.Entities.Select(a => a.AreaCode).Distinct();
            var targets = BrandService.Salers.Where(a => areaCodes.Contains(a.AreaCode)).Select(a => a.Email).ToArray();
            if (targets == null || targets.Length < 1) return;

            EmailSendDto sendDto = new EmailSendDto();
            sendDto.ToEmails = targets;
            sendDto.BodyFormat = EmailBodyFormat.Text;
            sendDto.Subject = "飞依诺-品牌部提醒您：你有新消息啦！";
            StringBuilder sb = new StringBuilder();
            eventData.Entities.ForEach(e =>
            {
                sb.AppendFormat("姓名:{0}、", e.Name);
                sb.AppendFormat("手机号:{0}、", e.Phone);
                sb.AppendFormat("邮箱:{0}、", e.Email);
                sb.AppendFormat("兴趣产品:{0}、", e.Type.ToDescription());
                sb.AppendFormat("地区名称:{0}、", e.AreaCity);
                sb.AppendFormat("公司名称:{0}、", e.Company);
                sb.AppendFormat("职位:{0}、", e.Position);
                sb.AppendFormat("其他需求:{0}、", e.Requirement);
                sb.AppendFormat("时间:{0}。", e.CreatedTime.ToString("yyyy-MM-dd HH:mm:ss"));
                sb.AppendFormat("\r\n");
            });
            sendDto.Body = sb.ToString();

            EmailSender.SendEmail(emailSender, sendDto);
        }
    }
}
